package com.attilax.util;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.attilax.coll.ListX;
import com.attilax.collection.listUtil;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.text.strUtil;
import com.attilax.web.ReqX;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * servlet
 * @author Administrator
 * 
 * com.attilax.util.connReduceDync
 *
 */
public class connReduceDync extends ConnReducerV2 {

	
//public String base;

//	.set_resfileUse(true)

	public static void main(String[] args) {
		
		connReduceDync c=new connReduceDync();
		c.res="com.attilax,core/import.js,core/core.js,core/yaml.js|com.atilax.frmwk,/jquery-1.8.3.min.js ";
		c.resfile="list/list_jss.txt";
		c.resfileUse=true;
	//	c.base = pathx.webAppPath();
		c.output="list/jobus_list.js";   //index/jobus.js
	//	c.output_css=c.base+"/list/jobus_list.css";
	//	c.isGeneCss=false;
		c.recreateMode=true;   //else use append mode
		c.genefile=true;
		
 	System.out.println(c.joinNout());   //trest mode
 //	System.out.println(c.readCacheOrjoinNout());	//product mode
		
//		Map m=Maps.newLinkedHashMap();
//		m.put("res",s);
		
		System.out.println("--f");

	}

	public String  readCacheOrjoinNout() {
		output=	fillFullpath(output);
		if(new File(this.output).exists())
			return filex.read(this.output);
		return joinNout();
	}
	
	public  String joinNoutV2() {
		this.resfileUse=true;
		resfileBaseUse=true;
		recreateMode=true;
		iniBase();
	
		gene() ;
		return this.resCache;
	}

	public  String joinNout() {
		iniBase();
	
		gene() ;
		return this.resCache;
	}
 
    int  jsCount;
    int cssCount;
	private void gene() {
		
		iniBase();
		 resfile=base+"/"+resfile;
		List<String> li=Lists.newLinkedList();
		if(resfileUse==false)
		  li=parseLi(base);
		if(resfileUse)
			li=listUtil.trimLine( filex.read2list(this.resfile) );
		if(li.size()==0)
			throw new RuntimeException("res file read is empty,makbe file not exist:"+this.resfile);
		for (String line : li) {
			line = line.trim();
			if(line.endsWith(".js"))
				jsCount++;
			if(line.endsWith(".css"))
				cssCount++;
			if (line.length() == 0)
				continue;
			importx(line);

		}
		calcRestype();
		reduce();
		
		
	}

	

	private void calcRestype() {
		if(jsCount>cssCount)
			this.restype="js";
		else
			this.restype="css";
		
	}

	private   List<String> parseLi(String base) {
		List<String> li=Lists.newArrayList();
		String reses=res;
		String[] rows=reses.split("\\|");
		for (String row : rows) {
			String[] cols=CsvUtil.toCols(row);
			String dir=cols[0];
		 
			for (int i=1;i<cols.length;i++) {
				 
				 
				String f = cols[i].trim();
				if(f.trim().startsWith("/"))
					f=f.substring(1);
				String full_file=dir+"/"+f;
				li.add(full_file);
			}
		}
		return li;
	}

}
